package org.grayrabbit.cloud.core.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

import org.grayrabbit.cloud.core.application.BizApplication;
import org.grayrabbit.cloud.core.command.CommandHandlerFactory;
import org.grayrabbit.cloud.core.module.ModuleConstructException;
import org.grayrabbit.cloud.utils.Console;
import org.grayrabbit.cloud.utils.logger.Output;


public class ServerConsole extends Console implements Output{

	public ServerConsole(String name, String url) throws ModuleConstructException {
		super(name);		
		new BizApplication(url,true).run();
	}

	public void writeln(String arg) throws IOException {
		System.out.println(arg);
	}
	
	public static void main(String[] args) throws Exception{
		
		long start = System.currentTimeMillis();
		System.setProperty("java.server.hostname",InetAddress.getLocalHost().getHostAddress());
		
		Runtime.getRuntime().addShutdownHook(new Thread(){
    		public void run(){
    			System.out.println(" bye bye :-) ");
    		}
    	});		
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		ServerConsole console = new ServerConsole("Server","server.xml");
		println(module+ " consume time "+ (System.currentTimeMillis()-start) + "ms running ... ");
		do {
            String command = "";
            try{
            	command = in.readLine();   
            }catch(Exception e){
            	
            }
            if(command != null && command.equals("quit")){
            	break;
            }
            else if(command != null && command.equals("exit")){
            	break;  
            }
            else{
            	CommandHandlerFactory.getLocalCommandHandler(console,true).handler(command);
            }
        } while (!Thread.interrupted());
		
		println(module+ " survive time "+ (System.currentTimeMillis()-start) + "ms ");
        System.exit(0);
	}

}
